package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务端接口实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 设置私有化微信登录路径
     */
    private static String WX_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //首先通过 code 获取当前用户的 openId
        String openId = getOpenId(userLoginDTO.getCode());
        //判断用户的 openId 是否存在
        if (openId == null) {
            //如果不存在则抛出异常
            throw new UserNotLoginException(MessageConstant.LOGIN_FAILED);
        }
        //再判断当前用户是否是新用户，新用户则自动注册
        User user = userMapper.selectUserByOpenId(openId);
        if (user == null) {
            //拼接用户数据
            user = User.builder().openid(openId).createTime(LocalDateTime.now()).build();
            //自动注册此用户
            userMapper.insertUser(user);
        }
        //最后返回这个用户信息
        return user;
    }

    /**
     * 获取微信登录的 openId
     * @return
     */
    private String getOpenId(String code){
        //设置 MAP 集合将需要的参数 赋值给 集合
        Map<String, String> paramMap = new HashMap<String, String>();
        //设置微信登陆的 ID
        paramMap.put("appid",weChatProperties.getAppid());
        //设置微信登录的密钥
        paramMap.put("secret",weChatProperties.getSecret());
        //设置微信登录的 code码
        paramMap.put("js_code",code);
        //设置微信登录的状态种类
        paramMap.put("grant_type","authorization_code");
        //向微信发送参数 以获取 openId
        String json = HttpClientUtil.doGet(WX_URL,paramMap);
        //因为返回的数据是 JSON 格式所以需要 JSON 格式转化
        JSONObject jsonObject = JSONObject.parseObject(json);
        //获取返回数据集合中的 openId
        String openId = jsonObject.getString("openid");
        //返回 openId
        return openId;
    }
}
